/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.collections;

import org.jetbrains.annotations.NotNull;

import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

import static java.util.Arrays.asList;

public class CompositeIterator<E> implements Iterator<E>
{
	private final List<Iterator<E>> iterators;
	private Iterator<E> currentIterator;
	private int currentIndex;

	public CompositeIterator(final @NotNull List<Iterator<E>> iterators)
	{
		this.iterators = iterators;
		currentIndex = -1;
		this.currentIterator = getNextIterator();
	}

	public boolean hasNext()
	{
		if (currentIterator == null)
		{
			return false;
		}
		final boolean hasNext = currentIterator.hasNext();
		if (!hasNext)
		{
			currentIterator = getNextIterator();
			return hasNext();
		}
		else
		{
			return true;
		}
	}

	@NotNull
	public E next()
	{
		if (currentIterator == null)
		{
			throw new NoSuchElementException();
		}
		return currentIterator.next();
	}

	public void remove()
	{
		throw new UnsupportedOperationException("remove");
	}

	private Iterator<E> getNextIterator()
	{
		currentIndex++;
		return (iterators.size() == currentIndex) ? null : iterators.get(currentIndex);
	}

	@SafeVarargs
	@NotNull
	public static <E> CompositeIterator<E> compositeIterator(final @NotNull Iterator<E>... iterators)
	{
		return new CompositeIterator<>(asList(iterators));
	}
}
